package com.dwd.pay.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.dwd.basic.constant.AlipayConfig;
import com.dwd.basic.service.impl.BaseServiceImpl;
import com.dwd.order.pojo.ProductOrder;
import com.dwd.pay.mapper.AlipayInfoMapper;
import com.dwd.pay.pojo.AlipayInfo;
import com.dwd.pay.service.IAliPayInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description: TODO
 * @Author 汶狄
 * @Date 2021/1/28 10:49
 * @Version 1.0
 */
@Service
public class AliPayInfoServiceImpl extends BaseServiceImpl<AlipayInfo> implements IAliPayInfoService {
    @Autowired
    private AlipayInfoMapper alipayInfoMapper;

    @Override
    public String goBuy(ProductOrder productOrder) {
        try {

            AlipayInfo alipayInfo = alipayInfoMapper.queryAliPayInfoByShopId(productOrder.getShop().getId());
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, alipayInfo.getAppid(),
                    alipayInfo.getMerchant_private_key(), "json", AlipayConfig.charset,
                    alipayInfo.getAlipay_public_key(), AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = productOrder.getOrderSn();
            //付款金额，必填
            String total_amount = productOrder.getPrice().toString();
            //订单名称，必填
            String subject = productOrder.getDigest();
            //商品描述，可空
            String body = productOrder.getDigest();

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
